import logging
import time
import json

from util.function import not_need_login, hash

from tornado.web import RequestHandler
from tornado.web import asynchronous
from tornado.gen import coroutine
from tornado.web import authenticated
from handlers import BaseHandler, UserBaseHandler


class SigninHandler(BaseHandler):

    def get(self):
        self.render('auth/signin.html', error=None)

    @asynchronous
    @coroutine
    def post(self):
        username = self.get_body_argument('username', default="")
        password = self.get_body_argument('password', default="")
        remember = self.get_body_argument('remember', default="off")

        user = yield self.db.member.find_one({"username": username})

        if not user:
            self.results['error'] = '用户不存在'
            self.render('auth/signin.html')

        check = yield self.backend.submit(hash.verify, password, user['password'])

        if check:
            session = self.set_session(user)

            if remember == "on":
                cookie_json = json.dumps(session)
                self.set_secure_cookie(
                    "user_info", cookie_json, expires_days=30, httponly=True)

            yield self.db.member.find_and_modify({"username": username}, {
                "$set": {
                    "logintime": time.time(),
                    "loginip": self.get_ipaddress()
                }
            })
            self.redirect("/home")

        self.results['error'] = '用户名或密码错误'
        self.render('auth/signin.html')


class SignupHandler(BaseHandler):

    error = {
        "passworddiff": "两次输入的密码不相同",
        "usernameused": "用户已经注册过啦",
        "shortpassword": "密码长度不能少于6个字符",
        "shortusername": "用户名长度不能少于6个字符"}

    def get(self):
        error_key = self.get_argument("error", default=None)
        error = self.error.get(error_key)
        self.render('auth/signup.html', error=error)

    @asynchronous
    @coroutine
    def post(self):
        username = self.get_body_argument("username", default="")
        password = self.get_body_argument("password", default="")
        repassword = self.get_body_argument("repassword", default="")

        if len(username) < 6:
            self.redirect("/auth/signup?error=shortusername")

        member = yield self.db.member.find_one({'username': username})
        # 用户名已存在
        if member:
            self.redirect("/auth/signup?error=usernameused")

        # 密码长度太短
        if len(password) < 6:
            self.redirect("/auth/signup?error=shortpassword")

        # 两次输入的密码不匹配
        if password != repassword:
            self.redirect("/auth/signup?error=passworddiff")

        # 加密密码
        password = yield self.backend.submit(hash.get, password)

        # 插入用户
        user = {
            "username": username,
            "password": password,
            "power": 0,
            "time": time.time(),
            "email": "",
            "signal": u"太懒，没有留下任何个人说明",
            "logintime": None,
            "loginip": self.get_ipaddress(),
            "flag": -1
        }

        result = yield self.db.member.insert(user)

        self.redirect('/auth/signin')


class SignoutHandler(UserBaseHandler):

    def get(self):

        self.session.delete('current_user')

        self.clear_cookie("user_info")

        self.redirect(self.get_argument("next", "/"))


class UserinfoHandler(UserBaseHandler):

    def get(self):
        self.render('auth/userinfo.html')

    @coroutine
    def post(self):
        realname = self.get_body_argument("realname", default="")
        mobile = self.get_body_argument("mobile", default="")
        company = self.get_body_argument("company", default="")
        field = self.get_body_argument("field", default="")
        age = self.get_body_argument("age", default="")
        grade = self.get_body_argument("grade", default="")
        interest = self.get_body_argument("interest", default="")

        # 插入用户
        userinfo = {
            "realname": realname,
            "mobile": mobile,
            "company": company,
            "field": field,
            "age": age,
            "grade": grade,
            "interest": interest,
            "loginip": self.get_ipaddress()
        }

        result = yield self.db.userinfo.insert(userinfo)

        if not result:
            self.redirect("auth/userinfo")


        yield self.db.member.find_and_modify({
            "username": self.current_user["username"]
        }, {
            "$set": {
                "flag": 0
            }
        })

        self.redirect("/home")
